<template>
  <div class="app-container">
    <!--工具栏-->
    <el-dialog
      title="请选择打印模板"
      :visible.sync="crud.printConfig.pringDialog"
      width="30%"
    >
      <jPrintConfig groupId="feeOrder"
                    v-if="crud.printConfig.pringDialog"
                    @getPrintId="crud.toPrint"
                    :isPreview="crud.printConfig.isPreview"
      ></jPrintConfig>
    </el-dialog>
    <el-dialog
      title="请选择打印模板"
      :visible.sync="pringDialog"
      width="30%"
    >
      <jPrintConfig groupId="feeOrder"
                    v-if="pringDialog"
                    @getPrintId="print"
      ></jPrintConfig>
    </el-dialog>
    <div class="head-container">
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="crud.toDetail('feeOrderDetail')"
          v-permission="permission.add"
        >
          新增
        </el-button>
        <el-button slot="left" class="filter-item" size="mini" type="warning" :disabled="crud.selections.length !== 1"
                   :loading="crud.copyLoading" @click="copyOrder(crud.selections)" v-permission="permission.add">
          复制
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="danger"
          :loading="crud.rejectLoading"
          icon="el-icon-remove-outline"
          @click="audit('PASS','审核')"
          :disabled="crud.selections.length < 1"
          v-permission="permission.pass"
        >
          审核
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          :loading="crud.rejectLoading"
          type="success"
          icon="el-icon-circle-check"
          :disabled="crud.selections.length < 1"
          @click="audit('REJECT','反审')"
          v-permission="permission.reject"
        >
          反审
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="editTime"
          v-permission="permission.edit"
        >
          修改时间
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-notebook-2"
          :disabled="crud.selections.length < 1"
          @click="tabInvoiceType('collectPrint',0)"
        >汇总打印</el-button>
      </crudOperation>
      <div v-if="!crud.props.searchToggle" v-formkey="{query:toQuery}">
        <el-form size="small" label-width="70px">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编号">
                <el-input v-model="query.code" placeholder="请输入单据编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="合同名称">
                <el-input v-model="query.name" placeholder="请输入合同名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="费用类型">
                <el-select v-model="query.type" class="filter-item" clearable placeholder="请选择合同类型" size="small"
                           style="width: 100%;"
                >
                  <el-option
                    v-for="item in dict.t_fee_order_type"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="供应商">
                <table-select
                  :tableColumns="
                  [
                  {prop:'code',label:'供应商编码',width: '100'},
                  {prop:'name',label:'供应商名称',width: '150'},
                  {prop:'address',label:'地址'},
                  ]"
                  labelKey="name"
                  valueKey="id"
                  width="700"
                  :value.sync="query.supplierIds"
                  placeholder="请选择客户"
                  :params="{isContact:'1,2'}"
                  url="api/dropDown/basCustomerList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户">
                <table-select
                  :tableColumns="
                  [
                  {prop:'code',label:'客户编码',width: '100'},
                  {prop:'name',label:'客户名称',width: '150'},
                  {prop:'address',label:'地址'},
                  {prop:'sCustomerName',label:'二批'},
                  ]"
                  labelKey="name"
                  valueKey="id"
                  width="700"
                  :value.sync="query.customerIds"
                  placeholder="请选择客户"
                  :params="{isContact:'0,2'}"
                  url="api/dropDown/basCustomerList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务员">
            <!-- <zSelect :clearable="false" collapseTags multiple :value.sync="saleUserIds" url="/api/dropDown/sysUserList" style="width:  100%;"/> -->
                                <table-select
                                  :tableColumns="[{prop:'name',label:'业务员名称',width: '280'}]"
                                  :value.sync="query.saleUserIds"
                                  placeholder="请选择业务员"
                                  url="/api/dropDown/sysUserList"
                                ></table-select>
                              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="区域">
                <treeselect
                  v-model="query.customerAreaIds"
                  :options="areaList"
                  style="width: 100%"
                  placeholder="区域"
                  :normalizer="normalizer"
                  multiple
                  @input="getArea"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" >
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="分类">
                <treeselect
                  v-model="customerTypeIds"
                  :options="customerTypeList"
                  placeholder="客户分类"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @input="val=>getNoStr(val,'customerTypeList','customerTypeIds')"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据类型">
                <el-select v-model="query.sourceType" class="filter-item" clearable placeholder="请选择单据类型" size="small"
                           style="width: 100%;"
                >
                  <el-option
                    v-for="item in dict.t_fee_order_source_type"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="来源编号">
                <el-input v-model="query.sourceCode" placeholder="请输入来源编号"></el-input>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态">
                <el-select v-model="query.orderStatus" class="filter-item" clearable placeholder="请选择状态" size="small"
                           style="width: 100%;">
                  <el-option
                    v-for="item in dict.common_order_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" style="margin-bottom: 5px">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户">
                <el-input v-model="query.customerKeyword" placeholder="请输入客户名称编码/助记符"></el-input>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="创建人">
                <zSelect :value.sync="query.createUserIds" multiple url="/api/dropDown/sysUserList" style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="创建日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.createStartTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.createEndTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="备注">
                <el-input v-model="query.remark" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="flex fow-reverse">
            <el-button
              class="filter-item"
              size="mini"
              type="primary"
              @click="queryReport"
              >搜索</el-button
            >
            <el-button
              class="filter-item"
              plain
              size="mini"
              type="primary"
              @click="resetQuery"
              style="margin-right:5px"
              >重置</el-button
            >
          </el-row>
        </el-form>
      </div>
      <!--表格渲染-->
      <el-table ref="table"
                :row-style="crud.rowClass"
                show-summary
                height="700"
                @row-click="row=>changeDetailQuery(row)"
                :summary-method="crud.sumRow"
                :row-class-name="crud.tableRowClassName"
                v-if="isShowTable"
                @header-dragend="changeColWidth"
                @contextmenu.native="showMenu"
                @sort-change="sortTab"
                border v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
                @row-dblclick="crud.toDetailPlus('feeOrderDetail',$event.id)"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55"/>
        <el-table-column type="index" width="60" label="序号"/>
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
          :sortable="item.sortable?'custom':false"
          :sort-orders="['descending', 'ascending', null]"
          sort-change="sort"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
            <template v-if="item.prop =='sort'">
              <div class="handle_move">
                <i :class="scope.row['sort']" />
              </div>
            </template>
            <template v-else>
              <span v-if="item.type == 1" style="margin-left: 10px">{{scope.row[`${item.prop}`]}}</span>
              <span v-if="item.type == 2" style="margin-left: 10px">{{ parseTime(scope.row[`${item.prop}`])}}</span>
              <span v-if="item.type == 3" style="margin-left: 10px">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
    <j-bill-detail url="/api/feeOrder/detail" type="get" :head="sonHead" :headerQuery="headerQuery" :params="detailParams" access="order.detailList"
    />
    <el-dialog title="修改时间" :visible.sync="showEditTime" width="60%">
      <el-form size="small" label-width="90px" :model="order" :rules="rules">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                v-model="order.startDate"
                type="date"
                style="width: 100%;"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker
                v-model="order.endDate"
                type="date"
                style="width: 100%;"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="showEditTime = false">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="editTimeConfirm">确认</el-button>
      </div>
    </el-dialog>

    <vue-context-menu :contextMenuData="contextMenuData"
                      @tableConfig="tableConfig"
                      @deletedata="deletedata"></vue-context-menu>

    <!-- 表格配置 -->
    <el-dialog title="表格配置"
               :visible.sync="tableConfigShow"
               width="60%">
      <j-table-column-config :columns.sync="crud.header"  @tabSave="tabSave" @pit="pit" />
    </el-dialog>

  </div>
</template>

<script>
import crudFeeOrder from '@/api/erp/feeOrder'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
import { publicListKey } from "@/utils/key"
import {getHeaderProperties} from "@/api/erp/headerProperties";
import  jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";
import {tablemixins} from "@/mixins/tablemixins";
import jBillDetail from "@/components/jBillDetail/jBillDetail";
import headConfig from '../../../headConfig'

import {getAreaTree} from "@/api/erp/basCustomerArea";
import { getCustomerTypeTree } from '@/api/erp/basCustomerType'
import Treeselect from "@riophae/vue-treeselect";
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '费用单',
  url: 'api/feeOrder',
  sort: 'id,desc',
  optShow: {
    add: false,
    edit: false,
    del: true,
    copy: false,
    leadingIn: true,//导入
    download: true,
    downloadDetail: true,
    print: true, // 打印
    printDetail: true, // 打印详情
    enable: false,
    disable: false,
    pass: false,
    reject: false
  },
  crudMethod: {...crudFeeOrder}
})
const defaultForm = {
  id: null,
  code: null,
  name: null,
  type: null,
  busDate: null,
  startDate: null,
  endDate: null,
  sourceType: null,
  sourceId: null,
  sourceCode: null,
  supplierId: null,
  supplierCode: null,
  supplierName: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  feeAmount: null,
  supplierRate: null,
  supplierAmount: null,
  ownRate: null,
  ownAmount: null,
  isDraw: null,
  drawDate: null,
  drawUserId: null,
  drawUserCode: null,
  drawUserName: null,
  cancelStatus: null,
  cancelDate: null,
  cancelUserId: null,
  cancelUserCode: null,
  cancelUserName: null,
  cancelAmount: null,
  unCancelAmount: null,
  isPrint: null,
  printCount: null,
  seq: null,
  orderStatus: null,
  remark: null,
  orderRemark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  auditUserId: null,
  auditUserCode: null,
  auditUserName: null,
  auditTime: null,
  closeUserId: null,
  closeUserCode: null,
  closeUserName: null,
  closeTime: null
}
export default {
  name: 'FeeOrder',
  components: {pagination, crudOperation, rrOperation, udOperation, jPrintConfig,jTableColumnConfig,getHeaderProperties, jBillDetail,Treeselect},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),publicListKey,tablemixins],
  dicts: ['common_yes_or_no', 'common_order_status', 't_fee_order_type', 't_fee_order_source_type'],
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      sonHead:[],
      permission: {
        add: ['admin', 'feeOrder:add'],
        edit: ['admin', 'feeOrder:edit'],
        del: ['admin', 'feeOrder:del'],
        import: ['admin', 'feeOrder:import'],
        export: ['admin', 'feeOrder:export'],
        copy: ['admin', 'feeOrder:copy'],
        upload: ['admin', 'feeOrder:upload'],
        download: ['admin', 'feeOrder:download'],
        pass: ['admin', 'feeOrder:pass'],
        reject: ['admin', 'feeOrder:reject'],
        closed: ['admin', 'feeOrder:closed'],
        invalid: ['admin', 'feeOrder:invalid'],
        stop: ['admin', 'feeOrder:stop'],
        recover: ['admin', 'feeOrder:recover'],
      },
      detailParams:{
        id:0
      },
      headerQuery: {
        modelName:'feeOrderDetail',
        url: "api/fee/feeOrderDetail",
        userId:this.$store.state.user.user.userId,
      },
      rules: {
        startDate: [
          {required: true, message: '开始时间不能为空', trigger: 'blur'}
        ],
        endDate: [
          {required: true, message: '截止时间不能为空', trigger: 'blur'}
        ],
      },
      order: {
        startDate: null,
        endDate: null
      },
      able: false,
      enable: false,
      showEditTime: false,
      areaList:[],
      customerTypeList:[],
      customerTypeIds: [],
      invoiceType: "collectPrint",
      printIds:[],
      pringDialog: false,
    }
  },
  watch: {},
  created() {
    this.getAreaList()
    getCustomerTypeTree({size:999}).then(res=>{
      this.customerTypeList = res
    })
    this.sonHead = headConfig['feeOrderDetail']
  },
  methods: {
    tabInvoiceType(val,isPreview){
      this.invoiceType = val
      this.isPreview = isPreview
      this.pringDialog = true;
    },
    print(val){
      if(val !== null){
        this.pringDialog=false
        localStorage.setItem(this.invoiceType,val)
        this.crud.doPrint(val,this.printIds,this.isPreview,this.invoiceType)
      }else {
        this.$message.error('请选择打印模板');
      }
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    changeDetailQuery(row){
      this.detailParams.id= row.id
      this.crud.selectRow(row)
    },
    getAreaList() {//区域
        getAreaTree().then(res => {
          this.areaList = res
        })
      },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    getNode(node, str) {
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          str = this.getNode(node.children[i], str);
        }
      }
      return (str += node.id + ",");
    },

    resetQuery() {
      this.customerTypeIds = [];
      this.crud.resetQuery();
    },
    queryReport() {
      this.crud.toQuery();
      this.crud.props.searchToggle = false;
    },
    getNoStr(val,type,prop){
      let str = ''
      val.forEach(item=>{
        const itemNode = this.getTreeName(this[type],item)
        str = this.getNode(itemNode,str)
      })
      this.query[prop] = str
    },
    getArea(val){
        let str = ''
        console.log(this.areaList)
        val.forEach(item=>{
          const itemNode = this.getTreeName(this.areaList,item)
          str = this.getNode(itemNode,str)
        })
        this.query.customerAreaIds = str
      },
    getTreeName(treeList,id){
      let _this=this
      for (let i = 0; i < treeList.length; i++) {
        let treeItem=treeList[i]
        if(treeItem.id===id){
          return treeItem
        }else{
          if(treeItem.children && treeItem.children.length>0){
            let res=_this.getTreeName(treeItem.children,id)
            if(res){
              return res
            }
          }
        }
      }
    },
    editTime() {
      this.showEditTime = true
    },
    editTimeConfirm() {
      var oDate1 = new Date(this.order.startDate);
      var oDate2 = new Date(this.order.endDate);
      if (oDate1.getTime() > oDate2.getTime()) {
        this.$message({
          message: '开始时间不能大于截止时间',
          type: 'warning'
        })
        return
      }
      let ids = []
      for (let i = 0; i < this.crud.selections.length; i++) {
        ids.push(this.crud.selections[i].id)
      }
      this.order.ids = ids
      crudFeeOrder.updateDate(this.order).then(res => {
        if (res.success) {
          this.showEditTime = false
          this.crud.refresh()
          this.$message.success("修改成功")
        } else {
          this.$message.error("修改失败")
        }
      }).catch(e => {
        this.$message.error("修改失败")
      })
    },
    getValue(e) {
      this.query.startTime = this.query.dataExtent[0]
      this.query.endTime = this.query.dataExtent[1]
    },
    audit(type, msg) {
      this.crud.rejectLoading = true
      const ids = this.crud.selections.map(m => m.id)
      const data = {
        ids: ids,
        type: type
      }
      crudFeeOrder.passOrReject(data).then(res => {
        if (200 === res.status) {
          this.crud.refresh()
          this.$message.success(msg + "成功")
        }
        this.crud.rejectLoading = false
      }).catch(e => {
        this.crud.rejectLoading = false
      })
    },
    copyOrder(e) {
      const { id } = e[0]
      this.crud.toCopy(id,"/fee/feeOrderDetail")
    }
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.flex {
  display: flex;
  justify-content: center;
}
.fow-reverse {
  flex-direction: row-reverse;
}
</style>
